<?php 
namespace tree;


class Tree
{
    public $arr;
    
    function __construct()
    {
        
    }
    public function init($data)
    {
        $narr = array();
        foreach ($data as $key => $value) {
            $narr[$value['id']] = $value;
        }
        $this->data = $narr;
    }
    /**
     * 获取指定id的子数组
     * @author cuibo weiai525@outlook.com at 2016-10-24
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function getChildren($id)
    {
        $narr = null;
        foreach ($this->data as $key => $value) {
            if ($id == $value['pid']) {
                $narr[$value['id']] = $value;
            }
        }
        return $narr;
    }
    /**
     * 得到整个子数组
     * @author cuibo weiai525@outlook.com at 2016-10-24
     * @param  integer $id 树开始id
     * @return array     树形数组
     */
    public function getTreeArray($id)
    {
        $lsdata = array();
        $children = $this->getChildren($id);
        if ($children == null) {
            return null;
        }else{
            foreach ($children as $key => $value) {
                $children[$key]['children'] = $this->getTreeArray($value['id']);
            }
        }
        return $children;
    }
    /**
     * 返回一维数组树
     * @author cuibo weiai525@outlook.com at 2016-11-06
     * @param  integer $id    [description]
     * @param  [type]  &$list [description]
     * @param  integer $deep  深度 即递归调用的深度，第一次为0
     * @return [type]         [description]
     */
    public function getTreeList($id = 0, &$list,$deep = 0)
    {
        $children = $this->getChildren($id);
        if ($children == null) {
            return null;
        }else{
            $deep = $deep + 1;
            foreach ($children as $key => $value) {
                $value['tree_deep'] = $deep-1;
                $list[] = $value;
                $this->getTreeList($value['id'],$list,$deep);
            }
        }
    }

    /**
     * 得到树的第一级
     * @author cuibo weiai525@outlook.com at 2016-11-14
     * @return array 
     */
    public function getFirst()
    {
        return $this->getChildren(0);
    }
}

